/**
 * 
 */
package com.effectiv.req1.event;

import jodd.bean.BeanTemplateParser;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import com.effectiv.req1.domain.ProjectActivity;
import com.google.common.eventbus.Subscribe;

/**
 * @author Dhrubo
 * 
 */
@Component
@Slf4j
public class UseCaseEventHandler implements EventHandler {

	@Autowired
	private MongoTemplate template;

	@Autowired
	private BeanTemplateParser parser;

	protected void process(AbstractEvent event) {
		String message = parser.parse(event.getTemplate(),
				event);

		log.info("Message produced = {}", message);

		ProjectActivity activity = BeanUtils.instantiate(ProjectActivity.class);
		activity.setActivityBy(event.getUseCase().getCreatedBy());
		activity.setActivityDetails(message);
		activity.setCreatedDate(event.getUseCase().getCreatedDate());
		activity.setProject(event.getUseCase().getProject());

		template.save(activity);
	}

	@Subscribe
	public void addNewUseCase(NewUseCaseEvent event) {
		log.info("Handling new use case event- {}", event);
		process(event);
	}

	@Subscribe
	public void updateUseCase(UpdateUseCaseEvent event) {
		log.info("Handling update use case event- {}", event);
		process(event);
	}
}
